﻿using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Reflection;

namespace DynamicExe
{
    class Program
    {
        private const string TestDynamicType = "Test.TestDynamic";
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                ShowUsage();
                return;
            }
            UsingReflection(args[0]);
            UsingReflectionWithDynamic(args[0]);

        }

        private static void UsingReflectionWithDynamic(string aNumber)
        {
            //throw new NotImplementedException();

            double x = 20;
            double y = 22.5;
            dynamic calc = GetTest(aNumber);
            double result = calc.Number(x, y);
            Console.WriteLine($"结果是：{x}+ {y} = {result}");

            try
            {
                result = calc.Multiply(x, y);
            }
            catch (RuntimeBinderException ex)
            {
                Console.WriteLine(ex);
            }
        }

        private static void UsingReflection(string aname)
        {
            string name = "田小伙子";
            int year = 56;
            object obj = GetTest(aname);

            //获取类型方法并输出
            object result = obj.GetType().GetMethod("NameAndYear").Invoke(obj, new object[] { name, year });
            Console.WriteLine($"姓名：{name} 年龄：{year} ");
            //throw new NotImplementedException();
        }

        private static object GetTest(string aname)
        {
            //throw new NotImplementedException();
            Assembly assembly = Assembly.LoadFile(aname);//加载文集程序集
            return assembly.CreateInstance(TestDynamicType);//创建一个字符串实例
        }

        private static void ShowUsage()
        {
            Console.WriteLine($"用法: dotnet run 绝对路径");
            Console.WriteLine();
            Console.WriteLine("Test.dll复制到外接程序目录");
            Console.WriteLine("并在启动应用程序加载库时传递此目录的绝对路径");
        }


    }
}
